package com.sen.app.timemail.utils;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

/**
 * freemarker模板读取工具
 * 
 * @author sen
 */
public final class FtlUtils {

	private static Logger logger = Logger.getLogger(FtlUtils.class);
	
	private static ResourceLoader resourceLoader = new DefaultResourceLoader();
	private static Configuration cfg;
	
	private static Map<String, Template> templates = new ConcurrentHashMap<String, Template>();
	
	private FtlUtils() {
		// empty!
	}
	
	public static Template getEmailHtmlTemplate() {
		return getTemplate("emailHtmlTemplate", "email/email-html.ftl");
	}
	
	private static Template getTemplate(String name, String ftlFilename) {
		initCfg();
		
		final String templateName = name;
		
		Template template = templates.get(templateName);
		if (template == null) {
			Template temp = null;
			try {
				temp = cfg.getTemplate(ftlFilename);
				temp.setOutputEncoding("UTF-8");
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
			templates.put(templateName, temp);
		}
		return templates.get(templateName);
	}
	
	private static void initCfg() {
		if (null == cfg) {
			cfg = new Configuration();
			try {
				File dir = resourceLoader.getResource("file:" + DirUtils.getFtlDir()).getFile();
				cfg.setDirectoryForTemplateLoading(dir);
				cfg.setDefaultEncoding("UTF-8");
				cfg.setNumberFormat("#");
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
			cfg.setObjectWrapper(new DefaultObjectWrapper());
		}
	}
}
